import { defineStore } from 'pinia'
export const useCartStore = defineStore({
  id: 'cart',
  state: () => {
    return {
      cartList: [],
      selectList: [],
      orderList: []//结算的商品
    }
  },
  getters: {
    ischeckAll () {
      return this.cartList.length === this.selectList.length
    },
    //计算总价
    totalPrice () {
      let total = {
        num: '',
        totalP: ''
      }
      this.orderList = JSON.parse(JSON.stringify(this.cartList.filter(item => item.check)))
      // this.orderList = this.cartList.filter(item => item.check)
      this.orderList.forEach(item => {
        item.number = 1
        item.id = item.courseId
      })
      total.totalP = this.orderList.reduce((t, i) => {
        return t += i.counter * i.discountPrice
      }, 0)
      total.num = this.orderList.reduce((t, i) => {
        return t += i.counter
      }, 0)
      return total
    }
  },
  actions: {
    addCartList (payload) {
      this.selectList = []
      payload.forEach(item => {
        item['check'] = true
        this.selectList.push(item.id)
      })
      this.cartList = payload
    },
    //全选
    all () {
      this.selectList = this.cartList.map(item => {
        item['check'] = true
        return item.id
      })
    },
    //全不选
    unAll () {
      this.selectList = []
      this.cartList.forEach(item => {
        item['check'] = false
      })
    },
    //单选
    itemChecked (index) {
      let id = this.cartList[index].id
      let idx = this.selectList.indexOf(id)
      if (idx > -1) {
        //如果找到了把那一项设置为选中状态设置为false
        this.cartList[index].check = false
        //从选中数组里面删除掉那一项
        this.selectList.splice(idx, 1)
      } else {
        //没找到就把那项设置为fasle
        this.cartList[index].check = true
        // 往选中数组里面push
        this.selectList.push(id)
      }
    }
  },
  persist: {
    enabled: true,
    strategies: [{
      key: 'xiaoluxian_cart',
      storage: localStorage,
    }]
  }
})